from flask import Flask, jsonify, request, Response
from database_operations import insert_news_data
from crawlArticles import crawlArticles
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

def CATEGORY_MAP():
    return {
        "国内": "2510",
        "国际": "2511",
        "社会": "2669",
        "体育": "2512",
        "娱乐": "2513",
        "军事": "2514",
        "科技": "2515",
        "财经": "2516",
        "股市": "2517",
        "美股": "2518"
    }

@app.route('/category_map', methods=['GET'])
def get_category_map():
    return jsonify(CATEGORY_MAP()), 200

@app.route('/crawl_articles', methods=['GET'])
def crawl_articles():
    category_name = request.args.get('lid', 2511)
    num = int(request.args.get('page', 1))
    def generate():
        for title in crawlArticles(category_name, num):
            yield f"{title}\n\n"
    return Response(generate(), mimetype='text/event-stream')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)